/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package examplesocket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author 5m
 */
public class ServerAccept extends Thread{

    Socket s;
    ServerSocket server;
    Stream sc;
    ConcurrentHashMap<String, Stream> listaClient;
    ConcurrentHashMap<Integer, Group> groupsMap;
    Pinger pg;
    Boolean stillRunning;
    Vector<String> connectedUsers;
    Vector<String> connectedIPUsers;
    Vector<User> registeredUsers;
    ServerAccept(ServerSocket server, ConcurrentHashMap<String, Stream> listaClient,Vector<User> registeredUsers)
    {
        this.server=server;
        stillRunning=true;
        this.listaClient = listaClient;
        connectedUsers = new Vector();
        connectedIPUsers = new Vector();
        this.registeredUsers=registeredUsers;
        groupsMap = new ConcurrentHashMap();
    }
    
    public void serviceStop()
    {
        stillRunning = false;
        Enumeration<Stream> listaStream = listaClient.elements();
        while(listaStream.hasMoreElements())
        {
            Stream tmpS = listaStream.nextElement();
            tmpS.stopStream();
        }
        try {
            server.close();
        } catch (IOException ex) {
            System.err.println("Error while closing SystemAccept");
        }
    }
    
    @Override
    public void run()
    {
        CryptHelper.getInstance().cryptHelperInitializer();
        Parser.getInstance().parserInitializer(connectedUsers, connectedIPUsers, registeredUsers, groupsMap, listaClient);
        while(stillRunning)
        {
            try {
                s = server.accept();
                User sockUser = new User(s.getRemoteSocketAddress().toString());
                sc = new Stream(s,sockUser);
                sc.startStream();
                listaClient.put(s.getRemoteSocketAddress().toString() + ":" + s.getPort(),sc);
                System.out.println("Connesso con successo:" + s.getRemoteSocketAddress().toString());
            }
            catch (IOException ex)
            {}
        }
    }
}